/**
 * Copyright(c) 2015 Jade Techonologies Co., Ltd.
 *
 * History:
 *   15-1-17 上午11:08 Created by lyyang
 */
package com.jade.framework.security.shiro.realm;

import com.jade.framework.security.shiro.authc.SessionIdToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * 支持cache的sessionid realm
 *
 * @author <a href="mailto:lyyang@jade.com">lyyang</a>
 * @version 1.0 15-1-17 上午11:08
 */
public class SessionIdRealm extends AuthorizingRealm
{
    public SessionIdRealm()
    {
        setAuthenticationTokenClass(SessionIdToken.class);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException
    {
        SessionIdToken token = (SessionIdToken) authenticationToken;

        Subject subject = new Subject.Builder().sessionId(token.getSessionId()).buildSubject();
        if (subject.isAuthenticated()) {
            return new SimpleAuthenticationInfo(subject.getPrincipal(), token.getSessionId(), getName());
        }
        return null;
    }
}
